#include "decipheraddon.h"

DecipherAddon::DecipherAddon()
{
    db = QSqlDatabase::database();
}

QString DecipherAddon::getAusgabe(const QString &gtin, const QString &addon) const
{
    if ( db.isOpen() )
    {
        QSqlQuery q(db);
        q.prepare("SELECT COUNT(*) FROM stammdaten WHERE vdznr = :vdznr;");
        q.bindValue("vdznr", getVdznr(gtin));
        if ( q.exec() && q.first() )
        {
            if ( q.value(0).toInt() > 1 )
                return QVariant(QVariant(addon.right(2)).toInt()).toString();
            else
                return QVariant(QVariant(addon.right(4)).toInt()).toString();
        }
    }
    return addon;
}

QString DecipherAddon::getObjektNr(const QString &gtin, const QString &addon) const
{
    if ( db.isOpen() )
    {
        QString multi;
        QSqlQuery q(db);        
        QString key;
        QString value = getVdznr(gtin);
        if ( value == gtin )
            key = "gtin";
        else
            key = "vdznr";
        q.prepare("SELECT COUNT(*) FROM stammdaten WHERE "+key+" = :value;");
        q.bindValue(":value", value);
        q.exec();
        q.first();
        if ( q.value(0).toInt() > 1 && addon.length() == 5 )
        {
            multi = addon.left(1);
        }

        if ( multi.isEmpty() )
            q.prepare("SELECT objektnr FROM stammdaten WHERE "+key+" = :value;");
        else
        {
            q.prepare("SELECT objektnr FROM stammdaten WHERE "+key+" = :value AND multi = :multi;");
            q.bindValue(":multi", multi);
        }
        q.bindValue(":value", value);
        if ( q.exec() && q.first() )
        {
            return q.value(0).toString();
        }
    }
    return QString();
}

QString DecipherAddon::getVdznr(const QString &gtin) const
{
    if ( isPresseGTIN(gtin) )
        return QString("%1").arg(gtin.mid(3,5).toInt());
    else
        return gtin;
}

bool DecipherAddon::isPresseGTIN(const QString &gtin) const
{
    return ( isGTIN(gtin) && (gtin.left(3) == "419" || gtin.left(3) == "414" || gtin.left(3) == "439" || gtin.left(3) == "434") );
}

bool DecipherAddon::isGTIN(const QString &check) const
{
    if ( check.length() == 13 || check.length() == 15 || check.length() == 18 )
    {
        int checksum = 0;
        for ( int i = 12; i >= 0; i-- )
        {
            int c = ((13-i)%2==0)?3:1;
            checksum += c * QVariant(check[i]).toChar().digitValue();
        }
        return (checksum%10==0);
    }
    else
    {
        return false;
    }
}
